package gameservice

import (
	"admin100/app/dao"
	"admin100/app/dao/centerdao"
	"admin100/app/dao/gamedao"
	"admin100/app/model/gamemodel"
	"admin100/app/service/centerservice"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"fmt"
	"strings"

	"github.com/gogf/gf/frame/g"
)

var Consume = &consumeService{}

type consumeService struct{}

type PropConsumeStatistics struct {
	OpType int     `json:"opType"`
	Count  int     `json:"count"`
	Rate   float32 `json:"rate"`
}

//获取道具
func (s *consumeService) GetPropConsumeStatistics(req *gamemodel.ConsumeAnalysisReq) []*PropConsumeStatistics {
	if req.PropType == 0 || req.PropId == 0 {
		defErr.Panic(define.SelectProp)
	}

	var (
		node   = centerservice.CGameServer.FetchNodeStrByPtIdAndSid(req.PlatformId, req.ServerId)
		gameDb = gamedao.NewConsumeStatistics(node)
		gcmn   = gameDb.Columns
	)

	m := gameDb.Where(g.Map{
		gcmn.Type:     req.Type,
		gcmn.PropType: req.PropType,
		gcmn.PropId:   req.PropId,
	})

	if req.PromoteId == 0 {
		m = m.Where("player_id in (select id from player where server_id = ? and channel in(?))", req.ServerId, strings.Split(req.ChannelList, ","))
	} else {
		promoteData, err := dao.PromoteData.Where(dao.PromoteData.Columns.Id, req.PromoteId).FindOne()
		if err != nil {
			defErr.Panic(define.DataOptFail, err.Error())
		}

		column := centerdao.GlobalAccount.Columns
		serverStr := ""
		for serverByte := range []byte(req.ServerId) {
			if serverStr == "" {
				serverStr = fmt.Sprintf("%v", serverByte)
			} else {
				serverStr = serverStr + "," + fmt.Sprintf("%v", serverByte)
			}
		}
		globalAccountList, err := centerdao.GlobalAccount.WhereValNotEmpty(g.Map{
			column.PlatformId:                     req.PlatformId,
			column.Promote:                        promoteData.Promote,
			column.RecentServerList + " like %?%": serverStr,
		}).FindAll()
		if err != nil {
			defErr.Panic(define.DataOptFail, err.Error())
		}

		accountList := make([]string, 0)
		for _, a := range globalAccountList {
			accountList = append(accountList, a.Account)
		}
		m = m.Where("player_id in (select id from player where server_id = ? and channel in(?) and acc_id in(?))", req.ServerId, req.ChannelList, accountList)
	}

	if req.PlayerId > 0 {
		m = m.Where("player_id = ?", req.PlayerId)
	}

	if req.Type == 0 {
		m.M = m.M.Order("count desc")
	} else {
		m.M = m.M.Order("count asc")
	}

	list := make([]*PropConsumeStatistics, 0)
	if err := m.Fields("log_type as op_type, sum(value) as count").Group(gcmn.LogType).Scan(&list); err != nil {
		defErr.Panic(define.DataOptFail, err.Error())
	}
	var sum = 0
	for _, e := range list {
		sum += e.Count
	}
	for _, e := range list {
		e.Rate = float32(e.Count) / float32(sum) * 100
	}

	return list
}
